package health_system.health_system.config;

import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * Custom WebSocket configurator that enables Spring dependency injection in WebSocket endpoints
 */
@Component
public class CustomWebSocketConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    
    private static final Logger logger = LoggerFactory.getLogger(CustomWebSocketConfigurator.class);
    private static volatile BeanFactory context;
    
    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        if (context == null) {
            throw new InstantiationException("ApplicationContext not injected. Make sure CustomWebSocketConfigurator is a Spring bean.");
        }
        
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            return super.getEndpointInstance(clazz);
        }
    }
    
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        try {
            // 从请求中获取用户名
            String username = extractUsername(request);
            
            if (StringUtils.hasText(username)) {
                // 将用户名存储在会话属性中
                sec.getUserProperties().put("username", username);
                logger.debug("WebSocket握手: 用户名设置为 {}", username);
            } else {
                logger.warn("WebSocket握手: 未找到用户名");
            }
        } catch (Exception e) {
            logger.error("WebSocket握手修改失败: {}", e.getMessage(), e);
        }
        
        // 调用父类方法完成握手
        super.modifyHandshake(sec, request, response);
    }
    
    /**
     * 从请求中提取用户名
     * @param request 握手请求
     * @return 用户名，如果不存在则返回null
     */
    private String extractUsername(HandshakeRequest request) {
        // 从查询参数中提取
        Map<String, List<String>> parameters = request.getParameterMap();
        if (parameters != null && parameters.containsKey("username")) {
            List<String> values = parameters.get("username");
            if (values != null && !values.isEmpty()) {
                return values.get(0);
            }
        }
        
        // 如果查询参数中没有，尝试从URI中提取
        String requestUri = null;
        if (request.getRequestURI() != null) {
            requestUri = request.getRequestURI().toString();
        }
        
        if (requestUri != null && requestUri.contains("username=")) {
            String[] parts = requestUri.split("username=");
            if (parts.length >= 2) {
                String username = parts[1];
                int ampIndex = username.indexOf('&');
                if (ampIndex != -1) {
                    username = username.substring(0, ampIndex);
                }
                return username;
            }
        }
        
        return null;
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CustomWebSocketConfigurator.context = applicationContext;
    }
} 